<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <!--<el-input v-model="listQuery.startTime" clearable size="mini" class="filter-item" style="width: 200px;" placeholder="请输入开始日期"/>
      <el-input v-model="listQuery.endTime" clearable size="mini" class="filter-item" style="width: 200px;" placeholder="请输入结束日期"/>-->
      <!--<div class="block">-->
      <!--<span class="demonstration"></span>-->
      <el-date-picker
        v-model="listQuery.startToEnd"
        type="daterange"
        align="right"
        unlink-panels
        range-separator=" 至 "
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions">
      </el-date-picker>
      <!--</div>-->
      <!--<el-select v-model="listQuery.batchNumber" placeholder="请选择产品批号">
        <el-option
          v-for="(value, key) in batchNumbers"
          :key="key"
          :label="value"
          :value="key">
        </el-option>
      </el-select>-->
      <!--<el-select v-model="type" placeholder="请选择查询方式" @change="handleChange">
        <el-option
          v-for="item in types"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>-->
      <!--<el-input v-model="listQuery.batchNumber" clearable size="mini" class="filter-item" style="width: 200px;" placeholder="请输入产品批号"/>-->
      <!--<el-input v-model="listQuery.batchNumber" clearable size="mini" class="filter-item" style="width: 200px;" placeholder="请输入产品批号"/>-->
      <!--  <el-input v-model="listQuery.userDepartments" clearable size="mini" class="filter-item" style="width: 200px;" placeholder="请输入使用部门"/>-->
      <el-button  class="filter-item" type="primary" icon="el-icon-search" @click="handleSelect">查找</el-button>
      <!--<el-button  class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button  class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">新建</el-button>-->
      <!--<el-button  class="filter-item" type="primary" icon="el-icon-edit" @click="handleEnd">月度报表</el-button>
      <el-button  class="filter-item" type="primary" icon="el-icon-edit" @click="handleEnd">周报表</el-button>
      <el-button  class="filter-item" type="primary" icon="el-icon-edit" @click="handleEnd">年度统计</el-button>-->
      <el-button :loading="downloadLoading"  class="filter-item" type="warning" icon="el-icon-download" @click="handleDownload">导出</el-button>

    </div>
    <!---->
    <!--<div v-for="o in 4" :key="o" class="text item">
      '' {{'列表内容 ' + o }}
    </div>-->
    <!-- 按每日汇总查询 -->
    <div>
      <el-card >
        <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中。。。" border fit
                  highlight-current-row :header-cell-style="{fontSize: '16px',color:'#333'}">
          <el-table-column align="center" min-width="120" label="起止日期" prop="date"/>
          <!--<el-table-column align="center" min-width="80" label="产品批号" prop="batchNumber"/>-->
          <el-table-column align="center" min-width="90" label="产品名称" prop="productName"/>
          <el-table-column align="center" min-width="70" label="生产量" prop="productCount"/>
          <el-table-column align="center" min-width="70" label="总件数" prop="totalPieces"/>
          <el-table-column align="center" min-width="70" label="总订量" prop="totalOrderCount"/>
          <el-table-column align="center" min-width="70" label="总分装量" prop="totalSplitCount"/>
          <el-table-column align="center" min-width="80" label="衰变量" prop="intervalDecay"/>
          <!--<el-table-column align="center" min-width="80" label="结余" prop="remainCount"/>-->
          <el-table-column align="center" label="操作" width="150" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleUpdate4(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="handleDelete2(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList"/>
      </el-card>
    </div>
    <!---->


    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100" />
    </el-tooltip>

  </div>
</template>

<style>
  .el-dialog {
    width: 60%;
  }
  .table-expand {
    font-size: 0;
  }
  .table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
  .gallery {
    width: 80px;
    margin-right: 10px;
  }
</style>

<script>

  import {listBachNumbers,listproductProductions, deleteProductProductions, setIsEnd,  insertAllproductProduction,publishproductProduction,getSortedList,listByOrders,listReportFormsWeek} from '@/api/business/productProduction'
  import BackToTop from '@/components/BackToTop'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import axios from 'axios'
  export const uploadFileRequest=(url, params)=>{
    return axios({
      method: 'post',
      url: '/productProduction/insertMany',
      data: params,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }
  export default {
    name: 'productProductionList',
    components: { BackToTop, Pagination },
    filters: {
      formatproductProductionType(productProductionType) {
        if (productProductionType === 1) {
          return '操作规程'
        } else if (productProductionType === 2) {
          return '管理器材'
        } else {
          return '规章制度'
        }
      },
      formatPerson(personId) {
        if (personId === 0) {
          return '正常'
        } else if (personId === 1) {
          return '已过期'
        } else {
          return '已下架'
        }
      }
    },
    data() {
      return {
        list: [],
        total: 0,
        listLoading: true,
        showCard1:true,
        showCard2:true,
        pickerOptions: {
          shortcuts: [{
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近半年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近二年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 360);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        value1: '',
        value2: '',
        loading:false,
        date: new Date(),
        showEditInput:false,
        files:[],
        newAttachmentsTable:[],
        listByDate:[],
        multipleSelection:[],
        insert:true,
        noPersonalInformation:[],
        listQuery: {
          page: '1',
          limit: '20',
          startToEnd:[],
          batchNumber:'',
          week:'',
          month:'',
          year:'',
          day:''
        },
        batchNumbers:[],
        type:'',
        types:[{ value: '按每日发货量',
          label: '按每日发货量'},
          { value: '按产品批次',
            label: '按产品批次'}],
        productProductionDetail: '',
        detailDialogVisible: false,
        downloadLoading: false,
        btnText:''
      }
    },
    created() {
      this.getList()
      /*this.getBatchNumbers()*/
      this.showCard1=true
      this.showCard2=false
    },
    methods: {

      handleChange(value) {
        // value是当前选中的值
        if(value=="按每日发货量") {
          this.showCard2=true
          this.showCard1=false
        }else if(value=="按产品批次"){
          this.showCard1=true
          this.showCard2=false
        }else{
          this.showCard1=true
          this.showCard2=true
        }
        // 在这里编写选中后的逻辑代码
      },
      handleSortChange({ name, order }) {
        this.listLoading = true
        if (order === 'ascending') {
          console.log(name)
          this.listQuery.sort=name
          this.listQuery.order='asc'
          listByOrders(this.listQuery).then(response=>{
            this.list=response.data.data.items
            this.total = response.data.data.total
            this.listLoading = false
          })
          /*this.tableData.sort((a, b) => a[prop] > b[prop] ? 1 : -1);*/
        } else if (order === 'descending') {
          /*this.tableData.sort((a, b) => a[prop] < b[prop] ? 1 : -1);*/
          console.log(name)
          this.listQuery.sort=name
          this.listQuery.order='desc'
          listproductProductions(this.listQuery).then(response=>{
            this.list=response.data.data.items
            this.total = response.data.data.total
            this.listLoading = false
          })
        } else {
          // 如果需要重置排序，可以重新获取数据或使用原始数据填充tableData
        }
      },
      handleSelect(){
        this.getList()
      },
      fetchSortedData(sortField, sortOrder) {
        /*axios.get('/api/data/sort', { params: { sortField, sortOrder } })*/
        getSortedList(sortField, sortOrder).then(response => {
          this.list = response.data.data.items; // 更新表格数据
        })
          .catch(error => {
            console.error('Error fetching sorted data:', error);
          });
      },
      getList() {
        this.listLoading = true
        listReportFormsWeek(this.listQuery).then(response => {
          this.list = response.data.data.items

          this.total = response.data.data.total

          this.listLoading = false
        }).catch(() => {
          this.list = []

          this.total = 0

          this.listLoading = false
        })
      },
      handleSelectionChange(val2) {
        this.multipleSelection = val2
        /*detailproductInfo(this.multipleSelection).then(response => {
          this.listProductCount = response.data.data.items
          this.listLoading = false

        }).catch(() => {
          console.log('getList catch')
          this.listProductCount = []
          this.total = 0
          this.listLoading = false
        })*/

      },
      handleEnd(){
        setIsEnd(this.multipleSelection).then(responese=>{
          /*this.list=responese.data;*/
        })
        this.getList()
      },
      onSuccess(response, file, fileList) {
        this.enabledUploadBtn = true;
        this.files=fileList;
        this.uploadBtnIcon = 'el-icon-upload2';
        this.btnText = '数据导入';
        insertAllproductProduction(data).then(response => {
          this.$notify.success({
            title: '成功',
            message: '创建成功'
          })
          this.$router.push({ path: '/productProduction/list' })
        }).catch(response => {
          MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
            confirmButtonText: '确定',
            type: 'error'
          })
        })
      },
      getBatchNumbers() {
        listBachNumbers(this.query).then(response => {
          this.batchNumbers = response.data.data.batchNumbers/*.sort((a, b) => new Date(a) - new Date(b))*/
          /*  this.batchNumbers2=this.batchNumbers.sort((a, b) => new Date(a) - new Date(b))*/
        }).catch(() => {
          console.log('getList catch')
          /*this.listStockss = []
          /!*this.total1 = 0*!/
          this.listLoading = false*/
        })

      },
      importData() {
        let myfile = this.$refs.myfile;
        let files = myfile.files;
        let file = files[0];
        const formData = new FormData()
        formData.append("file", file);
        this.uploadFileRequest("/productProduction/insertMany",formData).then(resp=>{
          if (resp) {
            console.log(resp);
          }
        })
      },
      /*   onError(err, file, fileList) {
           this.enabledUploadBtn = true;
           this.uplo<el-table-column align="center" min-width="200" label="剩余量" prop="remainQuantity" />adBtnIcon = 'el-icon-upload2';
           this.btnText = '数据导入';
         },*/
      beforeUpload(file) {
        this.enabledUploadBtn = false;
        this.uploadBtnIcon = 'el-icon-loading';
        this.btnText = '正在导入';
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleNew() {
        this.listQuery.isNew=1
        this.getList()
      },
      handleCreate() {
        this.$router.push({ path: '/iorders/create' })
      },
      handleUpdate2(row) {
        this.$router.push({ path: '/iorders/editproductProduction', query: { id: row.id }})
      },
      handleUpdate(row) {
        this.$router.push({ path: '/productProduction/update', query: { id: row.id }})
      },
      showDetail(detail) {
        this.productProductionDetail = detail
        this.detailDialogVisible = true
      },

      handleDelete(row) {
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
        this.$notify.success({
          title: '成功',
          message: '删除成功'
        })
      },
      handleDelete2(row) {
        const index = this.listByDate.indexOf(row)
        this.listByDate.splice(index, 1)
        this.$notify.success({
          title: '成功',
          message: '删除成功'
        })
      },
      handleDownload() {
        this.downloadLoading = true

        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['起止日期', '产品名称', '生产量', '总件数', '总订量', '总分装量', '衰变量']
          const filterVal = ['date', 'productName', 'productCount', 'totalPieces', 'totalOrderCount', 'totalSplitCount', 'intervalDecay']
          excel.export_json_to_excel2(tHeader, this.list, filterVal, '碘131化钠口服溶液周统计')
          this.downloadLoading = false
        })
      }
    }
  }
</script>
